<!--
 * @Description: 描述
 * @Author: liym
 * @Date: 2025-05-08 20:14:38
 * @LastEditors: liym
 * @LastEditTime: 2025-05-10 15:51:53
-->
<template>
  <view>
    {{ type }}
    <input v-model="scanResult" placeholder="识别结果将显示在此" />
    <button @click="chooseImage">上传本地图片识别</button>
    
    
  </view>
</template>

<script>
import { BrowserMultiFormatReader, BrowserQRCodeReader } from '@zxing/library';

export default {
  data() {
    return {
      orderInfo: null,
      orderForm: {

      },
      codeReader: null,
      scanResult: ''
    };
  },
  computed: {
    type () {
      if (this.orderInfo === null) return 'add'

      return 'edit'
    }
  },
  mounted () {
    this.orderInfo = uni.getStorageSync('order')
  },
  methods: {
    async uploadAndRecognize() {
      const file = await uni.chooseImage({ count: 1 });
	  console.log(file[1].tempFilePaths);
      const tempFilePath = file[1].tempFilePaths[0];
      
      // 转换为Blob URL
      const imageUrl = URL.createObjectURL(tempFilePath);
      
      try {
        const result = await this.codeReader.decodeFromImage(imageUrl);
        this.scanResult = result.text;
      } catch (e) {
        uni.showToast({ title: '识别失败', icon: 'none' });
      } finally {
        URL.revokeObjectURL(imageUrl); // 释放内存
      }
    },
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: async (res) => {
          const filePath = res.tempFilePaths[0]
          this.imageSrc = filePath

          // H5 平台支持 file 对象访问
          if (res.tempFiles && res.tempFiles.length > 0) {
            const file = res.tempFiles[0]
            const img = new Image()
            img.src = URL.createObjectURL(file)

            img.onload = async () => {
              try {
                const codeReader = new BrowserQRCodeReader()
                const result = await codeReader.decodeFromImageElement(img)
                this.scanResult = result.getText()
              } catch (err) {
                console.error('解析失败', err)
                this.result = '二维码识别失败'
              }
            }
          } else {
            this.result = 'H5 平台支持更好，App/小程序不支持 @zxing/library'
          }
        },
        fail: () => {
          this.result = '图片选择失败'
        }
      })
    }
  }
};
</script>